package com.chengliang.zuoye.handler;

import com.chengliang.zuoye.response.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 验证成功的处理
 */
public class SuccessHandler implements AuthenticationSuccessHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        String requestType = httpServletRequest.getHeader("X-Requested-With");
        //判断是否是ajax请求
        if("XMLHttpRequest".equals(requestType)){
            httpServletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter out = httpServletResponse.getWriter();
            out.write(JsonResult.ok().toString());
            out.flush();
            out.close();
        }else{
            //跳转主页
            httpServletResponse.sendRedirect("/");
        }
        logger.info("登录信息验证成功："+authentication);

    }

}
